<script setup>
name: 'users'
import { ref, reactive, onMounted } from 'vue'
import { getUserListAPI, addUserAPI, editUserStausAPI, queryUserAPI, editUserAPI, delUserAPI, allotRolesAPI } from '@/api/userAPI'
import { getRolesListAPI } from '@/api/authorityAPI'
import { ElMessage, ElMessageBox } from 'element-plus';

// 自定义验证guize
const checkEmail = (rule, value, callback) => {
    // 验证邮箱正则
    const regEmil = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

    if (regEmil.test(value)) {
        return callback()
    }
    callback(new Error('请输入合法的邮箱'))
}
// 自定义验证手机号规则
const checkMobile = (rule, value, callback) => {
    // 验证手机号正则
    const regMobile = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/

    if (regMobile.test(value)) {
        return callback()
    }
    callback(new Error('请输入合法手机号码'))
}
// 表单验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
    ],
    email: [
        { validator: checkEmail, trigger: 'blur' }
    ],
    mobile: [
        { validator: checkMobile, trigger: 'blur' }
    ]
})

// 获取用户数据列表
const userList = ref([])
const total = ref(0)
const queryInfo = ref({
    query: '',
    pagenum: 1,
    pagesize: 2
})
const getUserList = async () => {
    const { data: res } = await getUserListAPI(queryInfo.value)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    userList.value = res.data.users
    total.value = res.data.total
}

// 分页器
const handleSizeChange = (val) => {
    // console.log('handleSizeChange:'+ val);
    queryInfo.value.pagesize = val
    getUserList()
}
const handleCurrentChange = (val) => {
    // console.log('handleCurrentChange:'+val);
    queryInfo.value.pagenum = val
    getUserList()
}

// 添加用户
const abusersDialogVisible = ref(false)
const abusersForm = ref({
    username: '',
    password: '',
    email: '',
    mobile: ''
})

const abusersRef = ref(null)
const abusersDialogClose = () => {
    abusersRef.value.resetFields()
}
const abusers = () => {
    abusersRef.value.validate(async (valid) => {
        if (valid) {
            const { data: res } = await addUserAPI(abusersForm.value)
            if (res.meta.status !== 201) return ElMessage.error(res.meta.msg)
            ElMessage.success(res.meta.msg)
            abusersDialogVisible.value = false
            getUserList()
        }
    })
}

// 修改用户状态
const userStateChanged = async (row) => {
    const { data: res } = await editUserStausAPI(row.id, row.mg_state)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    ElMessage.success(res.meta.msg)
}

// 修改用户
const editDialogVisible = ref(false)
const editFrom = ref({})
const editDialog = async (row) => {
    const { data: res } = await queryUserAPI(row.id)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    editFrom.value = res.data
    editDialogVisible.value = true

}
const editRef = ref(null)
const editDialogClose = () => {
    editRef.value.resetFields()
}
const editUser = () => {
    editRef.value.validate(async (valid) => {
        if (valid) {
            const { id, email, mobile } = editFrom.value
            const { data: res } = await editUserAPI({ id, email, mobile })
            if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
            ElMessage.success(res.meta.msg)
            editDialogVisible.value = false
            getUserList()
        }
    })
}

// 删除用户
const delDialog = async (row) => {

    const confirmResult = await ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).catch(err => err)
    if (confirmResult === 'confirm') {
        const { data: res } = await delUserAPI(row.id)
        if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        getUserList()
    } else {
        ElMessage.info('已取消删除')
    }
}

// 分配角色
const allotDialogVisible = ref(false)

const allot = ref({
    id: '',
    username: '',
    role_name: ''
})

const allotDialog = (row) => {
    const { id, username, role_name } = row
    allot.value = {
        id,
        username,
        role_name
    }
    getRolesList()
    allotDialogVisible.value = true
}

// 获取角色列表数据
const rolesList = ref([])
const getRolesList = async () => {
    const { data: res } = await getRolesListAPI()
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    rolesList.value = res.data
}
const selectedRoleId = ref('')
const allotDialogClose = () => {
    rolesList.value = []
    selectedRoleId.value = ''
}
const allotRoles = async () => {
    if (!selectedRoleId) return ElMessage.error('请选择角色')
    const { data: res } = await allotRolesAPI(allot.value.id, selectedRoleId.value)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    ElMessage.success(res.meta.msg)
    allotDialogVisible.value = false
    getUserList()
}

onMounted(() => {
    getUserList()
})

</script>

<template>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <!-- 添加用户 -->
        <el-row :gutter="20">
            <el-col :span="9">
                <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
                    <template #append>
                        <el-button icon="Search" @click="getUserList" />
                    </template>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="abusersDialogVisible = true">添加用户</el-button>
            </el-col>
        </el-row>

        <!-- 表格区域 -->
        <el-table :data="userList" stripe border style="width: 100%">
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="username" label="姓名" width="180" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="mobile" label="电话" />
            <el-table-column prop="role_name" label="角色" />
            <el-table-column label="状态">
                <template v-slot="scope">
                    <el-switch v-model="scope.row.mg_state" class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        @change="userStateChanged(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button type="primary" icon="Edit" @click="editDialog(scope.row)"></el-button>
                    <el-button type="danger" icon="Delete" @click="delDialog(scope.row)"></el-button>
                    <el-tooltip class="box-item" effect="dark" content="分配角色" placement="top" :enterable="false">
                        <el-button type="warning" icon="Tools" @click="allotDialog(scope.row)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
            :page-sizes="[1, 2, 3, 5]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="abusersDialogVisible" title="添加用户" width="50%" @close="abusersDialogClose">
        <el-form :model="abusersForm" label-width="120px" :rules="rules" ref="abusersRef">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="abusersForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="abusersForm.password" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="abusersForm.email" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="abusersForm.mobile" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="abusersDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="abusers">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改用户" width="50%" @close="editDialogClose">
        <el-form :model="editFrom" label-width="120px" :rules="rules" ref="editRef">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="editFrom.username" disabled />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editFrom.email" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="editFrom.mobile" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="editUser">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog v-model="allotDialogVisible" title="分配角色" width="50%" @close="allotDialogClose">
        <div>
            <p>当前用户：{{ allot.username }}</p>
            <p>当前角色：{{ allot.role_name }}</p>
            <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id" />
            </el-select>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="allotDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="allotRoles">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped></style>